import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Query } from 'react-apollo'
import NewTeamMember from 'graphql/user/newTeamMember.graphql'
import QueryOrgUsers from 'graphql/user/queryNormalOrgMembers.graphql'
import QueryAllTeamMembers from 'graphql/user/queryAllTeamMembers.graphql'
import { Header, Image } from 'semantic-ui-react'
import {
  Form as FormTable,
  Section as TableSection,
  Switch,
  Submit,
  SearchInput,
} from 'components/tableForm'
import { global as globalDuck } from 'ducks'

const getVariables = (values) => {
  return {
    userId: values.name.value.id,
    name: values.name.value.name,
    role: values.role.value,
  }
}

const getOptions = (addedUsersData) => {
  const reducedMember = addedUsersData.team_member.map(member => member.user_id)
  return queryUsersData => queryUsersData.org_member.reduce((pre, next) => {
    const isAdded = reducedMember.includes(next.user_object.id) > 0
    console.log()
    pre.push({
      disabled: isAdded,
      text: next.user_object.name,
      value: next.user_object,
      content: (
        <Header as="h5" style={{ marginTop: '0' }}>
          <Image src={next.user_object.avatar} />
          <Header.Content>{next.user_object.name}</Header.Content>
        </Header>
      ),
      description: isAdded ? '已经添加' : '',
      icon: isAdded
        ? null
        : {
          name: 'add',
          className: 'right floated',
          color: 'green',
        },
    })
    return pre
  }, [])
}

class newDataset extends Component {
  componentDidMount = () => {}

  render() {
    const { org, match } = this.props
    const orgId = org.owner_object.id
    const orgName = org.owner_object.name
    let { path } = match.params
    path = path || ''
    const teamUrl = `/org/${orgName}/user/teams/list/${path}`
    return (
      <Query query={QueryAllTeamMembers} variables={{ id: orgId, path }}>
        {({ loading, error, data }) => {
          if (loading) return 'Loading....'
          if (error) return `Error! ${error.message}`
          return (
            <FormTable>
              <TableSection header="邀请成员">
                <SearchInput
                  name="name"
                  header="搜索成员"
                  description="请输入成员的名称或者邮箱"
                  query={{
                    query: QueryOrgUsers,
                    variables: { ownerId: orgId },
                    getData: getOptions(data),
                  }}
                />
                <Switch
                  name="role"
                  header="选择该成员的角色"
                  description="管理员角色拥有组织的全部权限"
                  options={[
                    { name: 'member', value: '普通成员' },
                    { name: 'admin', value: '管理员' },
                  ]}
                />
              </TableSection>
              <Submit
                submit={{
                  text: '添加',
                  variables: { ownerId: orgId, path },
                  getVariables,
                  mutation: NewTeamMember,
                  success: () => teamUrl,
                }}
                cancle={{ text: '取消', url: teamUrl }}
                redirect
              />
            </FormTable>
          )
        }}
      </Query>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(newDataset)
